import { useNotesStore } from '@/stores/notes'
import { ElMessage } from 'element-plus'

/**
 * 数据导入导出功能
 */
export function useDataExport() {
  const notesStore = useNotesStore()

  /**
   * 导出数据
   */
  const exportData = () => {
    try {
      const data = {
        notes: notesStore.notes,
        exportDate: new Date().toISOString(),
        version: '1.0'
      }
      const blob = new Blob([JSON.stringify(data, null, 2)], {
        type: 'application/json'
      })
      
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `web-notes-backup-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      ElMessage.success('数据导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    }
  }

  /**
   * 导入数据
   */
  const importData = (file: File): Promise<boolean> => {
    return new Promise((resolve) => {
      const reader = new FileReader()
      
      reader.onload = (event) => {
        try {
          const content = event.target?.result as string
          const data = JSON.parse(content)
          
          // 验证数据格式
          if (!data.notes || !Array.isArray(data.notes)) {
            ElMessage.error('文件格式不正确')
            resolve(false)
            return
          }
          
          // 确认导入
          ElMessage.success('数据导入成功')
          // 由于当前notes store没有importNotes方法，这里需要手动处理
          console.log('导入的数据:', data)
          resolve(true)
        } catch (error) {
          console.error('导入失败:', error)
          ElMessage.error('文件格式错误或导入失败')
          resolve(false)
        }
      }
      
      reader.onerror = () => {
        ElMessage.error('文件读取失败')
        resolve(false)
      }
      
      reader.readAsText(file)
    })
  }

  /**
   * 选择文件并导入
   */
  const selectAndImportFile = (): Promise<boolean> => {
    return new Promise((resolve) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.json'
      input.onchange = (event) => {
        const file = (event.target as HTMLInputElement).files?.[0]
        if (file) {
          importData(file).then(resolve)
        } else {
          resolve(false)
        }
      }
      input.click()
    })
  }

  /**
   * 清空所有数据
   */
  const clearAllData = async () => {
    try {
      // 由于当前notes store没有clearAllData方法，这里需要提示用户
      ElMessage.warning('清空数据功能需要在后端实现')
      console.log('清空数据功能待实现')
    } catch (error) {
      console.error('清空数据失败:', error)
      ElMessage.error('清空失败')
    }
  }

  /**
   * 获取存储使用情况
   */
  const getStorageInfo = () => {
    const notes = notesStore.notes
    const totalNotes = notes.length
    const totalWords = notes.reduce((sum, note) => sum + note.content.split(' ').length, 0)
    const favoriteNotes = notes.filter(note => note.isPublic).length
    
    // 提取所有标签
    const allTags = new Set<string>()
    notes.forEach(note => {
      note.tags?.forEach(tag => allTags.add(tag))
    })
    
    return {
      totalNotes,
      totalWords,
      favoriteNotes,
      categories: 0, // 暂时没有分类功能
      tags: allTags.size
    }
  }

  return {
    exportData,
    importData,
    selectAndImportFile,
    clearAllData,
    getStorageInfo
  }
} 